package com.yaorange.module.filter;

import com.yaorange.ma_util.util.JwtUtil;
import com.yaorange.ma_util.util.ThreadLocalUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtRequestFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        if (request.getMethod().equals("OPTIONS")){
            filterChain.doFilter(request, response);
            return;
        }

        String uri = request.getRequestURI().toString();
        if (uri.contains("login")){
            filterChain.doFilter(request, response);
            return;
        }
        String token = request.getHeader("token");
        if(token != null){
            try{
                Map<String, Object> claims = JwtUtil.parseToken(token);
                Integer userId = (Integer) claims.get("userId");
                Integer admin = (Integer) claims.get("admin");
                HashMap<String, Object> map = new HashMap<>();
                map.put("userId", userId);
                map.put("admin", admin);
                ThreadLocalUtil.set( map);
                filterChain.doFilter(request, response);
                ThreadLocalUtil.remove();
                return;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
